﻿/*
 * 版 本 v1.0
 * Copyright (c) 2013-2018 广州市同慧信息科技有限公司
 * 创建人：ftquan
 * 日 期：2017.04.17
 * 描 述：银行转账申请
 */
var acceptClick;
var keyValue = '';
var bootstrap = function ($, learun) {
    "use strict";
    var selectedRow = learun.frameTab.currentIframe().selectedRow;
    var page = {
        init: function () {
            page.initData();
            page.bind();
        },
        bind: function () {
            $("input").keydown(function () {
                if (13 == event.keyCode) {
                    var form = $("body");
                    var inputEles = form.find("input[disabled!='disabled']");
                    console.log("inputEles -> " + inputEles.length);  //5
                    for (var i = 0; i < inputEles.length; i++) {
                        if ($(inputEles[i]).is($(this))) {//判断两个jQuery对象是否相等用is
                            if (i == inputEles.length - 1) {
                                $(inputEles[0]).focus();
                            } else {
                                $(inputEles[i + 1]).focus();
                            }
                        }
                    }
                }
            });
            // 刷新
            $('#lr_refresh').on('click', function () {
                location.reload();
            });

            //保存录入过的信息，下一次录入时自动匹配
            $("#wtdwFullname").autocomplete({//为文本框完成绑定
                source: function(request,response){
                    //从request对象中获得文本框内容
                    var keyword = request.term;//广
                    //定义数组，封装最终结果
                    var obj = [];
                    var i;
                    $.ajax({
                        url: config.base_server() + 'ghyhzzsqs/findByWtdwFullname?wtdwFullname=' + keyword + '&access_token=' + config.getToken().access_token,
                        type:"get",
                        dataType:"json",
                        async:false,//关闭异步
                        success:function(res){
                            for(i in res.data){
                                //此处可以根据需要自定义要显示的内容以及封装的数据
                                obj.push({
                                    //label用于显示，value用于实际输入
                                    "label":"["+res.data[i].wtdwFullname+"-"+res.data[i].wtdwAccount+"-"+res.data[i].wtdwBank+"]",
                                    "value":res.data[i].wtdwFullname,
                                    "id": res.data[i].id
                                });
                                //label为提示显示的内容
                                //value为选中后补全出现在文本框中的内容
                            }
                        },
                    });
                    //将obj为结果返回
                    response(obj);
                },
                select : function(event, ui) { //event参数是事件对象，ui对象只有一个item属性，对应数据源中被选中的对象
                    var id = ui.item.id;
                    learun.httpAsyncGet2(config.base_server() + 'ghyhzzsqs/findById', '&id=' + id, function (res2) {
                        var wtdwFullname = res2.data.wtdwFullname;
                        var wtdwAccount = res2.data.wtdwAccount;
                        var wtdwBank = res2.data.wtdwBank;
                        $("#wtdwFullname").val(wtdwFullname);
                        $("#wtdwAccount").val(wtdwAccount);
                        $("#wtdwBank").val(wtdwBank);
                    })
                    return false;
                }
            });

            $("#money1").on("change", function () {
                $("#money2").val(keepTwoDecimalFull($("#money1").val() * 100));
                $("#money1").val(chineseNumber($("#money1").val()));
                $("#je").val($("#money2").val());
            });
            $("#lr_save").on("click", function () {
                alert("save");
            });
            // 打印
            $('#lr_print1').on('click', function () {
                var money1 = $("#money1").val();
                /*if (!money1) {
                    learun.alert.warning("请正确填写金额");
                    $("#money1").focus();
                    return;
                }*/
                String.prototype.replaceAll = function(s1,s2){
                    return this.replace(new RegExp(s1,"gm"),s2)
                };

                var hiprintTemplate = null;

                var postData = $('#form').lrGetFormData();
                $.lrSaveForm(config.base_server() + 'ghyhzzsqs/saveOrUpdate?keyValue=' + keyValue + '&access_token=' + config.getToken().access_token, JSON.stringify(postData), function (res) {
                    keyValue = res.data;
                    learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', '&code=pbill_yhzzsq_icbc', function (res1) {
                        if (res1.resp_code == 200) {
                            learun.httpAsyncGet2(config.base_server() + 'ghyhzzsqs/findById', "&id=" + keyValue, function (res) {
                                var temp = JSON.parse(res1.data.templete);
                                var wtdwBank = res.data.wtdwBank;

                                var temp2 = JSON.stringify(temp);
                                var temp3 = JSON.parse(temp2);
                                hiprintTemplate = new hiprint.PrintTemplate({
                                    //template: JSON.parse(res.data.templete),
                                    template: temp3,
                                    paginationContainer: '.hiprint-printPagination'
                                });

                                if (res.resp_code == 200) {
                                    hiprintTemplate.resetPage();

                                    var jsonData = [];
                                    var item = {};

                                    var count = 0;
                                    count = count + res.data.million5;
                                    res.data.million5 = count > 0 ? '' + res.data.million5 : '';
                                    count = count + res.data.million4;
                                    res.data.million4 = count > 0 ? '' + res.data.million4 : '';
                                    count = count + res.data.million3;
                                    res.data.million3 = count > 0 ? '' + res.data.million3 : '';
                                    count = count + res.data.million2;
                                    res.data.million2 = count > 0 ? '' + res.data.million2 : '';
                                    count = count + res.data.million1;
                                    res.data.million1 = count > 0 ? '' + res.data.million1 : '';
                                    count = count + res.data.thousand;
                                    res.data.thousand = count > 0 ? '' + res.data.thousand : '';
                                    count = count + res.data.hundred;
                                    res.data.hundred = count > 0 ? '' + res.data.hundred : '';
                                    count = count + res.data.ten;
                                    res.data.ten =  count > 0 ? '' + res.data.ten : '';
                                    count = count + res.data.yuan;
                                    res.data.yuan = count > 0 ? '' + res.data.yuan : '';
                                    count = count + res.data.jiao;
                                    res.data.jiao = count > 0 ? '' + res.data.jiao : '';
                                    count = count + res.data.fen;
                                    res.data.fen = count > 0 ? '' + res.data.fen : '';

                                    var money2 = res.data.money2;
                                    var strMoney = $.formatMoney(money2, 2).replace(".","").replace(",","");
                                    if(money2 <= 0.9){
                                        if(money2 >0.09){
                                            var str = strMoney.replace("0","");
                                        }else{
                                            var str = strMoney.replaceAll("0","");
                                        }
                                        var moneyLength = str.length;
                                        switch (moneyLength){
                                            case 1:
                                                res.data.jiao = "￥";
                                                break;
                                            case 2:
                                                res.data.yuan = "￥";
                                                break;
                                            case 3:
                                                res.data.ten = "￥";
                                                break;
                                            case 4:
                                                res.data.hundred = "￥";
                                                break;
                                            case 5:
                                                res.data.thousand = "￥";
                                                break;
                                            case 6:
                                                res.data.million1 = "￥";
                                                break;
                                            case 7:
                                                res.data.million2 = "￥";
                                                break;
                                            case 8:
                                                res.data.million3 = "￥";
                                                break;
                                            case 9:
                                                res.data.million4 = "￥";
                                                break;
                                            case 10:
                                                res.data.million5 = "￥";
                                                break;
                                        }
                                    }else if(money2 > 0.9){
                                        var moneyLength = strMoney.length;
                                        if(moneyLength > 8){
                                            moneyLength--;
                                        }
                                        switch (moneyLength){
                                            case 1:
                                                res.data.jiao = "￥";
                                                break;
                                            case 2:
                                                res.data.yuan = "￥";
                                                break;
                                            case 3:
                                                res.data.ten = "￥";
                                                break;
                                            case 4:
                                                res.data.hundred = "￥";
                                                break;
                                            case 5:
                                                res.data.thousand = "￥";
                                                break;
                                            case 6:
                                                res.data.million1 = "￥";
                                                break;
                                            case 7:
                                                res.data.million2 = "￥";
                                                break;
                                            case 8:
                                                res.data.million3 = "￥";
                                                break;
                                            case 9:
                                                res.data.million4 = "￥";
                                                break;
                                            case 10:
                                                res.data.million5 = "￥";
                                                break;
                                        }
                                    }

                                    /*item.year = res.data.year;
                                    item.month = res.data.month;
                                    item.day = res.data.day;*/
                                    var djrq = $('#djrq').val().replaceAll(' ', '');
                                    item.year = djrq.substring(0, 4);
                                    item.month = djrq.substring(4, 6);
                                    item.day = djrq.substring(6, 8);
                                    item.wtdwFullname = res.data.wtdwFullname;
                                    item.wtdwAccount = res.data.wtdwAccount;
                                    item.wtdwBank = res.data.wtdwBank;
                                    item.useStr = res.data.useStr;
                                    item.rph = res.data.rph;
                                    item.account = res.data.account;
                                    item.sprq = res.data.sprq;
                                    item.rpsjclrq = res.data.rpsjclrq;
                                    item.jby = res.data.jby;
                                    item.cshczy = res.data.cshczy;
                                    item.remark = res.data.remark;
                                    item.money1 = res.data.money1;
                                    item.money2 = res.data.money2;
                                    item.million5 = res.data.million5;
                                    item.million4 = res.data.million4;
                                    item.million3 = res.data.million3;
                                    item.million2 = res.data.million2;
                                    item.million1 = res.data.million1;
                                    item.thousand = res.data.thousand;
                                    item.hundred = res.data.hundred;
                                    item.ten = res.data.ten;
                                    item.yuan = res.data.yuan;
                                    item.jiao = res.data.jiao;
                                    item.fen = res.data.fen;
                                    jsonData.push(item);

                                    $('#myModal .modal-body .prevViewDiv').html(hiprintTemplate.getHtml(jsonData));

                                    if (res1.data.templeteBg) {
                                        var bgUrl = "";
                                        if(res1.data.templeteBg.indexOf("http")>-1){
                                            bgUrl = res1.data.templeteBg
                                        } else {
                                            bgUrl = config.base_server() + res1.data.templeteBg;
                                        }
                                        var bgArr = bgUrl.split(';');
                                        var _x = 0,_y = 0;
                                        if(bgArr.length>1){
                                            var locationArr = bgArr[1].split(',');
                                            _x = locationArr[0];
                                            _y = locationArr[1];
                                        }
                                        var _backgroudimg = bgArr[0];
                                        $(".hiprint-printPaper").css({"background-image":"url(" + _backgroudimg + "?access_token=" + config.getToken().access_token+")","background-repeat":"no-repeat","background-position":""+_x+"mm "+ _y+"mm"});
                                    }

                                    $('#myModal').modal('show');
                                }
                            });
                        }
                    });
                });
                $('#A4_printByHtml').click(function () {
                    hiprintTemplate.printByHtml($('#myModal .modal-body .prevViewDiv'));
                })
            });

        },
        initData: function () {
            $("#remark").val('');
            if (!!selectedRow) {
                keyValue = selectedRow.id;
                $('#form').lrSetFormData(selectedRow);

                $("#money1").val(chineseNumber($("#money2").val()));
            }
        }
    },
    // 保存数据
    acceptClick = function (callBack) {
        if (!$('#form').lrValidform()) {
            return false;
        }
        var postData = $('#form').lrGetFormData(keyValue);

        $.lrSaveForm(config.base_server() + 'ghxjckpts/saveOrUpdate?access_token=' + config.getToken().access_token + '&keyValue=' + keyValue, JSON.stringify(postData), function (res) {
            // 保存成功后才回调
            if (!!callBack) {
                callBack();
            }
        });
    };
    page.init();
}

function keepTwoDecimalFull(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
        alert('传递参数错误，请检查！');
        return false;
    }
    result = Math.round(num * 100) / 100;
    var s_x = result.toString(); //将数字转换为字符串
    var pos_decimal = s_x.indexOf('.'); //小数点的索引值
    // 当整数时，pos_decimal=-1 自动补0
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    // 当数字的长度< 小数点索引+2时，补0
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    jine = s_x * 100;
    return jine / 100;
}

function chineseNumber(dValue) {
    var maxDec = 2;
    dValue = dValue.toString().replace(/,/g, "");
    dValue = dValue.replace(/^0+/, "");
    if (dValue == "") {
        return "零";
    } else if (isNaN(dValue)) {
        return "错误：金额不是合法的数值！";
    }
    var minus = "";
    var CN_SYMBOL = "";
    if (dValue.length > 1) {
        if (dValue.indexOf('-') == 0) {
            dValue = dValue.replace("-", "");
            minus = "负";
        }
        if (dValue.indexOf('+') == 0) {
            dValue = dValue.replace("+", "");
        }
    }
    var vInt = "";
    var vDec = "";
    var resAIW;
    var parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;
    var NoneDecLen = (typeof (maxDec) == "undefined" || maxDec == null || Number(maxDec) < 0 || Number(maxDec) > 5);
    parts = dValue.split('.');
    if (parts.length > 1) {
        vInt = parts[0];
        vDec = parts[1];
        if (NoneDecLen) {
            maxDec = vDec.length > 5 ? 5 : vDec.length;
        }
        var rDec = Number("0." + vDec);
        rDec *= Math.pow(10, maxDec);
        rDec = Math.round(Math.abs(rDec));
        rDec /= Math.pow(10, maxDec);
        var aIntDec = rDec.toString().split('.');
        if (Number(aIntDec[0]) == 1) {
            vInt = (Number(vInt) + 1).toString();
        }
        if (aIntDec.length > 1) {
            vDec = aIntDec[1];
        } else {
            vDec = "";
        }
    } else {
        vInt = dValue;
        vDec = "";
        if (NoneDecLen) {
            maxDec = 0;
        }
    }
    if (vInt.length > 44) {
        return "错误：数值过大！整数位长【" + vInt.length.toString() + "】超过了上限！";
    }
    digits = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
    radices = new Array("", "拾", "佰", "仟");
    bigRadices = new Array("", "万", "亿", "兆", "京", "垓", "杼", "穰", "沟", "涧", "正");
    decimals = new Array("角", "分", "厘", "毫", "丝");
    resAIW = "";
    if (Number(vInt) > 0) {
        zeroCount = 0;
        for (i = 0; i < vInt.length; i++) {
            p = vInt.length - i - 1;
            d = vInt.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d == "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    resAIW += digits[0];
                }
                zeroCount = 0;
                resAIW += digits[Number(d)] + radices[modulus];
            }
            if (modulus == 0 && zeroCount < 4) {
                resAIW += bigRadices[quotient];
            }
        }
        resAIW;
    }
    for (i = 0; i < vDec.length; i++) {
        d = vDec.substr(i, 1);
        if (d != "0") {
            resAIW += digits[Number(d)] + decimals[i];
        }
    }
    if (resAIW == "") {
        resAIW = "零";
    }
    if (vDec == "") {
        resAIW;
    }
    console.log(CN_SYMBOL)
    console.log(minus)
    console.log(resAIW
    )

    resAIW = CN_SYMBOL + minus + resAIW;
    return resAIW;
}


function chineseNumber(n) {
    n = n.toString().replace(/,/g, "");
    n = n.replace(/^0+/, "");
    if (n == "") {
        return "零";
    } else if (isNaN(n)) {
        return "错误：金额不是合法的数值！";
    }
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);
    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}

